package com.game.dao.user;

import com.coment.game.user.UserExtends;
import com.coment.po.UserInfo;
import com.xs.action.exection.ActionException;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;


@Repository
public interface UserDao extends MongoRepository<UserInfo, Integer> {

    /// 创建用户
    default UserInfo tryCreateUser(UserInfo userInfo) {
        return findById(userInfo.getId()).orElseGet(() -> {
            UserExtends userExtends = new UserExtends();
            userExtends.setScore(0L);
            userInfo.setUserExtends(userExtends);
            userInfo.setId(userInfo.hashCode());
            this.insert(userInfo);
            return userInfo;
        });
    }

    /// 获取用户-必须返回
    default UserInfo findByIdMust(Integer integer) {
        Optional<UserInfo> optional = findById(integer);
        return optional.orElseThrow(() -> new ActionException("玩家不存在"));
    }

    /// 返回所有
    @Aggregation(pipeline = {
            "{ $match: { '_id': { $gt: 0 } } }",
            "{ $project: { '_id': 1 } }"
    })
    java.util.List<Integer> findAllIds();

    List<UserInfo> findAllByApiTypeAndNameLike(String apiType, String name);

    List<UserInfo> findAllByNameLike(String name);
}
